package com.crc.luojian.web;

import com.crc.luojian.beans.model.ApplicationContext;
import com.crc.luojian.method.MethodHanderAdapter;
import com.crc.luojian.method.MethodHandler;
import com.crc.luojian.method.MethodHandlerMappering;
import com.crc.luojian.util.ApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.applet.AppletContext;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

/**
 * @program: luojian-springframework
 * @description:
 * @author: luojian58
 * @create: 2021-06-10 10:42
 */
public class DisPatcherServlet extends HttpServlet {


    private MethodHanderAdapter methodHanderAdapter = new MethodHanderAdapter();
    public DisPatcherServlet() throws ServletException {

    }
    /**
     * @Author luojian
     * @Description 初始化
     * @Date  2021/6/10 18:25
     * @Param []
     * @return void
     **/
    @Override
    public void init() throws ServletException {

    }

    /**
     * @Author luojian
     * @Description 处理请求
     * @Date  2021/6/10 18:24
     * @Param [req, resp]
     * @return void
     **/
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String url = req.getRequestURI();
        MethodHandler methodHandler = ApplicationContextUtils.getMapping().getByUrl(url);
        if(null == methodHandler){
            throw new RuntimeException(" url :"+url+" hander can not found");
        }

        try {
            methodHanderAdapter.handler(req,resp,methodHandler);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
